import { createRouter, createWebHistory } from 'vue-router'

const Layout = () => import('../views/layout')
const Home = () => import('../views/home')
const TopCategory = () => import('../views/category/index.vue')
const SubCategory = () => import('../views/category/sub.vue')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login/index')
const LoginCallback = () => import('@/views/login/callback')
import store from '../store'
const routes = [
  // 一级路由布局容器
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        name: 'home',
        component: Home
      },
      {
        path: '/category/:id',
        name: 'topCategory',
        component: TopCategory
      },
      {
        path: '/category/sub/:id',
        name: 'subCategory',
        component: SubCategory
      },
      {
        path: '/product/:id',
        name: 'goods',
        component: Goods
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  { 
    path: '/#/login/callback',
    name: 'loginCallback',
    component: LoginCallback
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior () {
    return { left: 0, top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  if (to.name === 'login') {
    // 如果要去的路由是login，将当前路径存储在vuex上
    store.commit("user/setRedirectUrl", router.currentRoute.value.fullPath)
  }
  next()
})

export default router
